import base64
import os
from mimetypes import guess_type
import requests
from fastapi import HTTPException

IMAGE_DIR = r"D:\aaaaazzz\zhongji2\sources"
def get_image_as_base64(file_path):
    """
    将指定路径的图片文件转换为 base64 编码，并加上 MIME 类型前缀。

    参数:
        file_path (str): 图片文件的完整路径

    返回:
        str: base64 编码的图片数据（带 data URI 前缀），失败时返回 None
    """
    # file_path_true=os.path.join(IMAGE_DIR,file_path)
    file_path_true=file_path
    if not os.path.exists(file_path_true):
        return None

    # 自动检测文件类型（png, jpeg 等）
    mime_type, _ = guess_type(file_path_true)
    if mime_type is None or not mime_type.startswith("image/"):
        return None

    try:
        with open(file_path_true, "rb") as image_file:
            encoded_str = base64.b64encode(image_file.read()).decode("utf-8")
            return f"data:{mime_type};base64,{encoded_str}"
    except Exception as e:
        print(f"Error reading image file: {e}")
        return None

def download_image(url: str, save_path: str):
    """
    从指定URL下载图片并保存到本地

    参数:
        url: 图片的URL地址
        save_path: 保存图片的本地路径（包含文件名和扩展名）
    """
    try:
        # 发起HTTP请求获取图片数据
        response = requests.get(url, stream=True)
        response.raise_for_status()  # 如果响应状态码不是200，将抛出异常

        # 写入图片数据到本地文件
        with open(save_path, 'wb') as file:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    file.write(chunk)

        print(f"图片已成功保存至 {save_path}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"系统错误: {e}")
        # print(f"下载图片时发生错误: {e}")

